﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using Microsoft.Phone.Controls;

namespace Phone.Framework.Behaviors
{
    public class ApplicationBarButtonIconSwitchBehavior : Behavior<PhoneApplicationPage>
    {

        public string Text { get; set; }

        public bool CanSwitch
        {
            get { return (bool)GetValue(CanSwitchProperty); }
            set { SetValue(CanSwitchProperty, value); }
        }

        public static readonly DependencyProperty CanSwitchProperty =
            DependencyProperty.Register("CanSwitch", typeof(bool), typeof(ApplicationBarButtonIconSwitchBehavior),
            new PropertyMetadata(false, (sender, args) => {
                var behavior = sender as ApplicationBarButtonIconSwitchBehavior;
                behavior.SwitchIcon();
            }));

        private void SwitchIcon()
        {
            var button = this.AssociatedObject.ApplicationBar.FindButton(this.Text);

            //this.AssociatedObject.ApplicationBar.SwitchButtonIcon("Add History",
            //    CanSwitch,
            //    "Resources/Icons/appbar.favs.remove.rest.png",
            //    IconUri);

            if (originilIconUri == null)
            {
                originilIconUri = button.IconUri;
                originilText = button.Text;
            }
            if (CanSwitch)
            {
                button.IconUri = IconUri;
                if (!string.IsNullOrEmpty(SwitchText))
                {
                    Text = SwitchText;
                    button.Text = SwitchText;
                }
            }
            else
            {
                button.IconUri = originilIconUri;
                Text = originilText;
                button.Text = originilText;
            }
        }

        private Uri originilIconUri;
        private string originilText;

        public Uri IconUri { get; set; }

        public string SwitchText { get; set; }
    }
}
